<template>
  <el-upload
    class="avatar-uploader"
    action="http://upload.qiniup.com"
    :data="uploadData"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { GetQiniuToken } from "@/api/common";

export default {
  props: {
    imgUrl: {type:String,default:""}
  },
  watch: {
    imgUrl: {
      handler(newValue) {
        if(newValue) {
          this.imageUrl = newValue;
        }
      },
      // immediate: true
    }
  },
  data() {
    return {
      imageUrl: "",
      uploadData: {}
    }
  },
  beforeMount() {
    this.getToken();
  },
  methods: {
    getToken() {
      const requestData = {
        ak: "DuFWI5f-hGsmx-fFelLZxeoDB3JWfHhn--jJpnc_",
        sk: "Kzjx6JtJSgWULSYhXrgnMP6gDewNHNMmUpb0r9_5",
        buckety: "bydcarsimages"
      }
      GetQiniuToken(requestData)
        .then((res) => {
          const {token} = res.data;
          if(token) {
            this.uploadData.token = token;
          }
        })
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = `http://qkwea8wnx.hd-bkt.clouddn.com/${res.key}`;
      this.$emit("update:value", this.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      let fileName = file.name;
      let key = encodeURI(fileName);
      this.uploadData.key = key;
      return isJPG && isLt2M;
    }
  }
}
</script>

<style lang="scss" scoped>

</style>